package jcurses.widgets;

import java.util.StringTokenizer;

import jcurses.system.CharColor;
import jcurses.system.Toolkit;
import jcurses.util.Rectangle;

/**
 * This class implements a label widget
 */
public class Label extends Widget {

	private String text = null;

	private static CharColor __labelDefaultColors = new CharColor(
			CharColor.WHITE, CharColor.BLACK);

	/**
	 * The constructor
	 * 
	 * @param label
	 *            label's text
	 */
	public Label(String label) {
		this(label, null);
	}

	/**
	 * The constructor
	 * 
	 * @param label
	 *            label's text param colors label's colors
	 */
	public Label(String label, CharColor colors) {
		if (label != null) {
			text = label;
		} else {
			text = "";
		}
		setColors(colors);
	}

	public CharColor getDefaultColors() {
		return __labelDefaultColors;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
		this.setSize(getPreferredSize());
	}

	protected void doPaint() {
		Rectangle rect = getSize().clone();
		rect.setLocation(getAbsoluteX(), getAbsoluteY());
		Toolkit.printString(text, rect, getColors());
	}

	protected void doRepaint() {
		doPaint();
	}

	protected Rectangle getPreferredSize() {
		if (text.indexOf("\n") == -1) {
			return new Rectangle(text.length(), 1);
		} else {
			StringTokenizer tokenizer = new StringTokenizer(text, "\n");
			int width = 0;
			int height = 0;
			while (tokenizer.hasMoreElements()) {
				String token = tokenizer.nextToken();
				height++;
				if (token.length() > width) {
					width = token.length();
				}
			}
			height = (height == 0) ? 1 : height;
			return new Rectangle(width, height);
		}
	}

}
